package com.njym.java.security.admin.rest;

import com.alibaba.fastjson.JSON;
import com.njym.java.security.admin.biz.LecturerBiz;
import com.njym.java.security.admin.entity.Lecturer;
import com.njym.java.security.common.msg.ObjectRestResponse;
import com.njym.java.security.common.rest.BaseController;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("lecturer")
public class LecturerController extends BaseController<LecturerBiz, Lecturer> {

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Object add(@RequestBody String data){
        Lecturer entity = JSON.parseObject(data, Lecturer.class);
        entity.setAttr2(getPinYinHeadChar(JSON.parseObject(data).get("name").toString()).toUpperCase());
        try {
            baseBiz.insertSelective(entity);
            return new ObjectRestResponse<>().rel(true);
        }catch (RuntimeException e){
            return new ObjectRestResponse<>().rel(false);
        }

    }


    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    @ResponseBody
    public Object edit(@RequestBody String data){
        Lecturer entity = JSON.parseObject(data, Lecturer.class);
        entity.setAttr2(getPinYinHeadChar(JSON.parseObject(data).get("name").toString()).toUpperCase());
        try {
            baseBiz.updateById(entity);
            return new ObjectRestResponse<>().rel(true);
        }catch (RuntimeException e){
            return new ObjectRestResponse<>().rel(false);
        }
    }



    /**
     * 中文转首字符
     * @param str
     * @return
     */
    public static String getPinYinHeadChar(String str) {
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }
}